<?php
namespace App\Service;

class HwzdService extends BaseService
{
    //货物字典

    //列表
    public static function index($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = self::dbConn(self::$dbHuowu)->where('del', 0);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return self::toback(-2, '没有货物');
        }
        $arys = [];
        foreach ($res as $v) {
            $arys[] = [
                'id' => $v->id, 
                'title' => $v->title,
                'hw_code' => $v->hw_code,
                'imgs' => $v->imgs ? explode(';', $v->imgs) : [],
            ];
        }
        return self::toback(0, '', $arys, $total);
    }

    //添加
    public static function add($pas)
    {
        $res = (array) self::dbConn(self::$dbHuowu)
            ->where('del', 0)
            ->where('hw_code', $pas['hw_code'])
            ->first();
        if (!empty($res)) {
            return self::toback(-2, '存在同号记录');
        }
        $pas['uptime'] = $pas['addtime'] = toDate();
        $res = self::dbConn(self::$dbHuowu)->insertGetId($pas);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    //修改
    public static function modify($id, $pas)
    {
        $res = (array) self::dbConn(self::$dbHuowu)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return self::toback(-2, '记录不存在');
        }
        $pas['uptime'] = toDate();
        $res = self::dbConn(self::$dbHuowu)
            ->where('id', $id)
            ->update($pas);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    //删除
    public static function del($id)
    {
        $res = (array) self::dbConn(self::$dbHuowu)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return self::toback(-2, '没有数据');
        }
        $pas['del'] = 1;
        $pas['deltime'] = toDate();
        $res = self::dbConn(self::$dbHuowu)
            ->where('id', $id)
            ->update($pas);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }
}